from math import tan
import math
SCREEN_SIZE =  (640, 480)
CUBE_SIZE = 300

import pygame
import time
import sys
from pygame.locals import *
from gameobjects.vector3 import Vector3

from math import *
from random import randint


def calculate_viewing_distance(fov, screen_width):

    d = (screen_width/2.0) / tan(fov/2.0)
    return d


def run():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0)
    screen.fill((0, 0, 0))
    ball = pygame.image.load("ball.png").convert_alpha()
    ball_w, ball_h = ball.get_size()
    ball_center_x = ball_w / 2
    ball_center_y = ball_h / 2
    points = []
    for x in range(0, CUBE_SIZE+1, 20):
        points.append(Vector3(x, 0, 0))
        points.append(Vector3(x, 300, 0))
        points.append(Vector3(x, 0, 300))
        points.append(Vector3(x, 300, 300))
        points.append(Vector3(0, x, 0))
        points.append(Vector3(0, x, 300))
        points.append(Vector3(300, x, 0))
        points.append(Vector3(300, x, 300))
        points.append(Vector3(0, 0, x))
        points.append(Vector3(0, 300, x))
        points.append(Vector3(300, 0, x))
        points.append(Vector3(300, 300, x))

    for point in points:
        point = point + (0,0,700)
        point = point + (-150,0,0)

     # Sort points in z order
    def point_z(point):
        return point.z
    points.sort(key=point_z, reverse=True)

    while True:
        viewing_distance = calculate_viewing_distance(math.radians(90),SCREEN_SIZE[0])
        center_x, center_y = SCREEN_SIZE
        center_x /= 2
        center_y /= 2

        for event in pygame.event.get():
            time.sleep(0.0001)
            if event.type == QUIT or ( event.type == KEYDOWN and event.key == K_ESCAPE ) :
                    return
        # Draw the 3D points
        for point in points:
            x,y,z = point + ( 150,150,700)
#            x,y,z = point
            if z > 0:
                x =  x * viewing_distance / z
                y = y * viewing_distance / z
                screen.blit(ball, (x-ball_center_x, y-ball_center_y))
        pygame.display.update()



if __name__ == "__main__":
    run()

    